/**
 * 返回所有子路由
 */
export const getChildrenRoutes = (routes) => {
  const result = []
  routes.forEach((route) => {
    if (route.parent) {
      result.push(route)
    }
  })
  return result
}

/**
 * 判断数据是否为空值
 */
function isNull(data) {
  if (!data) return true
  if (JSON.stringify(data) === '{}') return true
  if (JSON.stringify(data) === '[]') return true
  return false
}

/*
  返回一级路由同时不要path为 /*和 ''的一级路由  同时也不要子路由
*/

export const filterRoutes = (routes) => {
  const childrenRoutes = getChildrenRoutes(routes)
  return routes.filter((route) => {
    if (route.path === '' || route.path === '*') return false
    return (
      !route.parent &&
      !childrenRoutes.find((childrenRoute) => {
        return childrenRoute.path === route.path
      })
    )
  })
}

/* * 根据 filterRoutes后的数据，返回对应 menu 规则数组 */

export const generateMenus = (routes = []) => {
  const filtersRoutes = filterRoutes(routes)
  const childrenRoutes = getChildrenRoutes(routes)
  const allroutes = [...filtersRoutes, ...childrenRoutes]
  // 遍历路由表
  allroutes.forEach((item) => {
    if (isNull(item.meta)) return

    if (item.parent) {
      // debugger
      const parentPath = item.parent.path
      const parentRoute = allroutes.find((route) => route.path === parentPath)
      // console.log(parentRoute)
      if (!parentRoute.children) parentRoute.children = []
      const isHave = parentRoute.children.find((route) => {
        return route.path === item.path
      })
      if (!isHave) {
        parentRoute.children[parentRoute.children.length] = item
      }
    }
  })
  console.log('allroutes', allroutes)
  return allroutes.slice(0, allroutes.length - childrenRoutes.length)
}
